/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
 * Description: The operator factory
 */

#include "framework/graph/operator_factory.h"
#include "common/debug/log.h"

using namespace std;

namespace hiai {
GRAPH_API_EXPORT OperatorFactory* OperatorFactory::Instance()
{
    static OperatorFactory instance;
    return &instance;
}

GRAPH_API_EXPORT shared_ptr<ge::Operator> OperatorFactory::CreateOperator(
    const std::string& opType, const std::string& name)
{
    // 先根据OpType查找CREATOR_FUN，然后调用CREATOR_FUN创建Operator
    std::map<std::string, CREATOR_FUN>::const_iterator iter = creatorMap_.find(opType);
    if (iter != creatorMap_.end()) {
        return iter->second(name);
    }
    FMK_LOGE("create operator failed, type : %s !", opType.c_str());
    return nullptr;
}

// 该函数仅在全局OperatorRegisterar对象的构造函数内调用，不涉及并发，所以无需加锁
GRAPH_API_EXPORT void OperatorFactory::RegisterCreator(const std::string& type, CREATOR_FUN fun)
{
    if (creatorMap_.find(type) != creatorMap_.end()) {
        FMK_LOGW("OperatorFactory::RegisterCreator: %s creator already exist", type.c_str());
        return;
    }

    creatorMap_[type] = fun;
}
} // namespace hiai
